package com.dfrz.problem.interceptor;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.dfrz.problem.utils.IConstant;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.TextParseUtil;

public class CheckSessionInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4873521022225292889L;
	
	private Set<String> execludeUrls = new HashSet<String>();

	public void setExecludeUrls(String execludeUrls) {
		this.execludeUrls = TextParseUtil.commaDelimitedStringToSet(execludeUrls);
	}

	private boolean applyUrl(String url){
		if (execludeUrls.contains("*") ) {
            return true;
        }

        for ( String pattern : execludeUrls) {
            if (pattern.equals(url)) {
                return true; 
            }
        }
        return false;
	}
	
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String actionName = invocation.getProxy().getActionName();
		String namespace = invocation.getProxy().getNamespace().substring(1);
		
		ActionContext actionContext = ActionContext.getContext();
		String url = namespace.length()>0?namespace+"/"+actionName:actionName;
		boolean b = applyUrl(url);
		
		if(b){
			return invocation.invoke();
		}
		
		Map<String, Object> session = actionContext.getSession();
		if(session.containsKey(IConstant.KEY_SES_LOGIN_USER)){
			return invocation.invoke();
		}else{
			return Action.LOGIN;
		}
	}

}
